#!/bin/bash

set -e

echo "🚀 Starting deployment verification..."

# 配置
BASE_URL=${1:-"http://localhost:3000"}
API_KEY=${2:-"test-api-key"}

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 测试函数
test_endpoint() {
  local endpoint=$1
  local expected_status=${2:-200}
  local description=$3
  
  echo -n "Testing $description... "
  
  response=$(curl -s -w "%{http_code}" -o /tmp/response "$BASE_URL$endpoint")
  
  if [ "$response" -eq "$expected_status" ]; then
    echo -e "${GREEN}✓${NC}"
    return 0
  else
    echo -e "${RED}✗ (got $response, expected $expected_status)${NC}"
    return 1
  fi
}

test_authenticated_endpoint() {
  local endpoint=$1
  local expected_status=${2:-200}
  local description=$3
  
  echo -n "Testing $description... "
  
  response=$(curl -s -w "%{http_code}" -o /tmp/response \
    -H "Authorization: Bearer $API_KEY" \
    "$BASE_URL$endpoint")
  
  if [ "$response" -eq "$expected_status" ]; then
    echo -e "${GREEN}✓${NC}"
    return 0
  else
    echo -e "${RED}✗ (got $response, expected $expected_status)${NC}"
    return 1
  fi
}

# 基础健康检查
echo "📋 Basic Health Checks"
test_endpoint "/api/health" 200 "Health endpoint"
test_endpoint "/api/health/simple" 200 "Simple health endpoint"
test_endpoint "/api/metrics" 200 "Metrics endpoint"

# API 端点测试
echo -e "\n🔌 Plugin API Tests"
test_endpoint "/api/plugins" 200 "Plugin list endpoint"

# 前端测试
echo -e "\n🌐 Frontend Tests"
test_endpoint "/" 200 "Homepage"

# 性能测试
echo -e "\n⚡ Performance Tests"
echo -n "Testing response time... "
start_time=$(date +%s%N)
curl -s "$BASE_URL/api/health" > /dev/null
end_time=$(date +%s%N)
duration=$(( (end_time - start_time) / 1000000 ))

if [ $duration -lt 100 ]; then
  echo -e "${GREEN}✓ (${duration}ms)${NC}"
else
  echo -e "${YELLOW}⚠ (${duration}ms - slower than expected)${NC}"
fi

# 并发测试
echo -n "Testing concurrent requests... "
for i in {1..10}; do
  curl -s "$BASE_URL/api/health" > /dev/null &
done
wait

echo -e "${GREEN}✓${NC}"

# 监控系统测试
echo -e "\n📊 Monitoring System Tests"
echo -n "Testing Prometheus metrics format... "
if curl -s "$BASE_URL/api/metrics" | grep -q "baihu_requests_total"; then
  echo -e "${GREEN}✓${NC}"
else
  echo -e "${RED}✗${NC}"
fi

echo -n "Testing health check structure... "
if curl -s "$BASE_URL/api/health" | grep -q '"status"'; then
  echo -e "${GREEN}✓${NC}"
else
  echo -e "${RED}✗${NC}"
fi

echo -e "\n🎉 Deployment verification completed!"
